<?php
/**
 * Copyright (c) 2006-2007, Julien PORTALIER
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright    Copyright (c) 2006-2007, Julien PORTALIER
 * @link         http://featherphp.googlecode.com/
 * @license      http://www.opensource.org/licenses/mit-license.php The MIT License
 * 
 * @deprecated ?
 */

/**
 * Manages sessions.
 */
class SessionComponent
{
	function startup(Controller $Controller)
	{
		# has a session already been started?
		$sid = session_id();
		if (!empty($sid))
			return;
		
		# config
		ini_set('session.name', Core::session_cookie);
		ini_set('session.use_only_cookies', '1');
		
		$expire = is_string(Core::session_expire) ?
			strtotime(Core::session_expire) : Core::session_expire;
		session_set_cookie_params($expire, Core::session_path, Core::session_domain);
		
		# webservice?
		if (isset($Controller->params['url']['session_id']))
		{
			if (!empty($Controller->params['url']['session_id']))
				session_id($Controller->params['url']['session_id']);
		}
		
		# autostart?
		if (Core::session_auto)
			$this->start();
	}
	
	function start()
	{
		session_start();
		
		# browsers may cache pages, proxies may not
		header('Pragma: ');
		header('Expires: ');
		header('Cache-Control: s-maxage=1, proxy-revalidate');
#		header("X-LIGHTTPD-SID: ".session_id());
		
		# sec. 1: prevent session fixation (session must exist)
		if (!isset($_SESSION['Config.init']))
		{
			session_regenerate_id(true);
			$_SESSION['Config.init'] = true;
		}
		
		# sec. 2: prevent session hijacking (UA musn't change between requests)
		if (isset($_SERVER['HTTP_USER_AGENT']))
		{
			if (isset($_SESSION['Config.UA']))
			{
				if ($_SESSION['Config.UA'] != md5($_SERVER['HTTP_USER_AGENT']))
				{
					session_regenerate_id(true);
					$_SESSION['Config.init'] = true;
					$_SESSION['Config.UA']   = md5($_SERVER['HTTP_USER_AGENT']);
				}
			}
			else {
				$_SESSION['Config.UA'] = md5($_SERVER['HTTP_USER_AGENT']);
			}
		}
	}
	
	function write($key, $value)
	{
		$_SESSION[$key] = $value;
	}
	
	function read($key)
	{
		return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
	}
	
	function delete($key)
	{
		unset($_SESSION[$key]);
	}
	
	function check($key)
	{
		return isset($_SESSION[$key]);
	}
	
	function setflash($mesg, $code=null)
	{
		$_SESSION['Flash.mesg'] = $mesg;
		$_SESSION['Flash.code'] = $code;
	}
	
	function flash($fancy=true)
	{
		if (isset($_SESSION['Flash.mesg']))
		{
			$mesg = $_SESSION['Flash.mesg'];
			$code = $_SESSION['Flash.code'];
			unset($_SESSION['Flash.mesg'], $_SESSION['Flash.code']);
			return $fancy ? '<p class="message'.(empty($code) ? null : " $code").
				'" id="message"><span>'.$mesg.'</span></p>' : $mesg;
		}
	}
}
?>